package com.example.demo.web;

import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @author KaiJu 2019/9/26 18:13
 * @program demo
 * @filename com.example.demo.web.aa
 * @description
 * @lastmodify 2019/9/26 18:13
 */

public class CompressUtils {

    public static String compress(String str)  {
        if (str == null || str.length() == 0) {
            return str;
        }
        Base64 base64encoder = new Base64();
        ByteArrayOutputStream out = null;
        GZIPOutputStream gzip = null;
        String rntStr = null;
        try {
            out = new ByteArrayOutputStream();
            gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes("UTF-8"));
            gzip.close();
            rntStr = new String(base64encoder.encode(out.toByteArray()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                gzip.close();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return rntStr;
//        return str+"压缩了";
    }

    /**
     * GZip 解压 xml
     * @param srcStr
     * @return
     * @
     */
    public static String uncompress(String srcStr)  {

        if (srcStr == null || srcStr.length() == 0) {
            return srcStr;
        }
        String rntStr = null;
        try {
            Base64 base64encoder = new Base64();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] bytes = base64encoder.decode(srcStr.getBytes());
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            GZIPInputStream gunzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            rntStr = out.toString("utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rntStr;
//        return srcStr+"解压了";
    }
}
